<template>
<!--过滤栏-->
        <div class="filter-container">
            <div class="filter-item item-input">
                <el-input v-model="tclassInput" placeholder="请输入教学班名称"></el-input>
            </div>
            <div class="filter-item item-button">

                <el-button type="primary" @click="searchClass()"><i class="el-icon-search"></i> 搜索</el-button>
            </div>
            <div class="filter-item item-button">
                <el-button type="primary" @click="requestTclass(), tclassInput = ''"><i class="el-icon-refresh"></i> 刷新
                </el-button>
            </div>
        </div>
  <!--教学班列表-->
        <div class="exam-list">
            <el-table
                    :data="tclassDetail.data"
                    border
                    style="width: 100%;">
                <el-table-column
                        label="序号"
                        width="60"
                        align="center">
                    <template #default="scope">
                        {{scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column
                        prop="name"
                        label="教学班名称"
                        width="280"
                        align="center">
                    <template #default="scope">
                        <el-tooltip content="点击查看已布置的作业" placement="top">
                            <span class="col2-cell-style"
                                  @click="viewHomeworkByClass(scope.$index)">{{scope.row.name}}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="createTime"
                        label="创建时间" a
                        width="200"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="updateTime"
                        label="结束时间"
                        width="200"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="teacherName"
                        label="任课老师"
                        width="150"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="status"
                        label="状态"
                        align="center">
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.status === 1" disable-transitions>正常</el-tag>
                        <el-tag type="danger" v-else-if="scope.row.status === 0" disable-transitions>异常</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="360">
                    <template #default="scope">
                        <el-button
                                size="small"
                                type="primary"
                                @click="assignHomework(scope.$index)">布置作业
                        </el-button>
                        <el-button
                                size="small"
                                type="success"
                                @click="downloadExcel(scope.$index)">下载成绩
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!--分页-->
        <Pagination :currentPage="currentPage" :pageSize="pageSize" :total="total"
                    :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></Pagination>

        <!--查看该班有哪些作业  对话框-->
        <el-dialog title="查看已布置作业" v-model="toViewHomeworkByClass" width="80%" top="2vh" @close = "closeHomeworkDialog">
            <el-table :data="tclassHomeworkDetail.data"
                      @selection-change="handleSelectionChange"
                      ref="multipleTable">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column property="id" label="作业id" width="100" align="center"></el-table-column>
                <el-table-column property="title" label="题目名称" width="220">
                    <template v-slot="scope">
                        <el-tooltip content="查看该作业所有学生的提交情况" placement="top">
                            <span class="col2-cell-style"
                                  @click="viewStudentByHomework(scope.$index), eidInput = ''">{{scope.row.title}}</span>
                        </el-tooltip>

                    </template>
                </el-table-column>
                <el-table-column property="beginTime" label="开始时间" width="220" align="center"></el-table-column>
                <el-table-column property="endTime" label="结束时间" width="200" align="center"></el-table-column>
                <el-table-column
                        prop="status"
                        label="状态"
                        align="center">
                    <template v-slot="scope">
                        <el-tag type="success" disable-transitions v-if="scope.row.status == 1">正常</el-tag>
                        <el-tag type="danger" disabel_transitions v-if="scope.row.status == 0">结束</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="400">
                    <template v-slot="scope">
                        <el-tooltip content="修改作业期限" placement="top">
                            <el-button
                                    size="small"
                                    type="primary"
                                    @click="changeHomeworkTime(scope.$index)">修改
                            </el-button>
                        </el-tooltip>
                        <el-button
                                size="small"
                                type="danger"
                                @click="toDeleteHomework = true, curHomeworkIndex = scope.$index">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <Pagination :currentPage="HomeworkCurrPage" :pageSize="HomeworkPageSize"
                        :total="HomeworkTotal" :handleSizeChange="handleSizeChange4"
                        :handleCurrentChange="handleCurrentChange4"></Pagination>

            <template #footer>
                <el-button type="primary" @click="toViewCloneHomeworkPage = true">克隆作业</el-button>
                <el-button type="primary" @click="downloadExcelBySelectedProblemId()">下载指定题目的学生成绩</el-button>
                <el-button @click="toViewHomeworkByClass = false">取 消</el-button>
            </template>
        </el-dialog>
        <!-- 删除作业 对话框 -->
        <el-dialog title="" v-model="toDeleteHomework" top="18vh" width="33%" center :show-close="false">
            <div class="take-up-header">
                <div class="header-icon">
                    <span class="icon-text">!</span>
                </div>
            </div>
            <div class="take-up-content">是否删除本次作业？删除之后学生将无法提交作业，如果已有学生提交则无法删除</div>
            <template #footer>
                <el-button type="primary" @click="deleteHomework(curHomeworkIndex)">确定删除</el-button>
                <el-button type="info" @click="toDeleteHomework = false">取消</el-button>
            </template>
        </el-dialog>
        <!--修改作业期限 对话框-->

        <el-dialog title="修改作业期限" v-model="toChangeHomeworkTime">
            <el-form ref="homeworkForm.data" :model="homeworkForm.data" status-icon :rules="homeworkRules">
                <el-form-item label="作业名称" :label-width="formLabelWidth" prop="name" style="width: 90%">
                    <span>&nbsp;{{homeworkForm.data.name}}&nbsp;&nbsp;&nbsp;</span>
                </el-form-item>
                <el-form-item label="班级" :label-width="formLabelWidth" prop="tclass">
                    <span>&nbsp;{{ homeworkForm.data.tclass }}&nbsp;&nbsp;&nbsp;</span>
                </el-form-item>
                <el-form-item label="起止时间" :label-width="formLabelWidth" prop="dateTime">
                    <el-date-picker
                            v-model="homeworkForm.data.dateTime"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="选择语言" :label-width="formLabelWidth" style="width: 90%">
                    <div class="filter-bar">
                        <el-select
                                v-model="homeWorklanguage"
                                multiple
                                collapse-tags
                                collapse-tags-tooltip
                                :max-collapse-tags="3"
                                placeholder="Select"
                                style="width: 240px"
                                >
                                <el-option
                                v-for="item in languageOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                />
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="创建人" :label-width="formLabelWidth" prop="teacher" style="width: 90%">
                    <span>&nbsp;{{ homeworkForm.data.teacher }}&nbsp;&nbsp;&nbsp;</span>
                </el-form-item>

            </el-form>
            <template #footer>
                <el-button @click="toChangeHomeworkTime = false, clearHomeworkForm()">取 消</el-button>
                <el-button type="primary" @click="changeHomeworkTimeComfirm()">修 改</el-button>
            </template>
        </el-dialog>

        <!-- 查看作业的提交情况 -->
        <el-dialog title="查看作业详情" v-model="toViewHomeworkDetail" fullscreen>
            <template #title>
                <span>{{ homeworkTitle }}</span>
            </template>

            <!--过滤栏-->
            <div class="filter-bar">

                <!-- 重新请求一次 -->
                <el-button type="primary" class="filter-item item-margin-left-16"
                           @click="viewStudentByHomework(curHomeworkIndex), eidInput = ''">
                    <i class="el-icon-refresh"></i> 刷新
                </el-button>
                <el-tooltip content="下载本次作业的重复率检测报告" placement="top">
                    <el-button type="primary" class="filter-item item-margin-left-16" @click="downloadRepCheckReport">
                        <i class="el-icon-s-opportunity"></i> 查重报告
                    </el-button>
                </el-tooltip>
                <el-button type="primary" class="filter-item item-margin-left-16" @click="toViewHomeworkDetail = false">
                    <i class="el-icon-circle-close"></i> 关闭页面
                </el-button>
            </div>
            <!--学生表格-->
            <el-table
                    :data="studentDetail.data"
                    border
                    style="width: 100%"
                    id="exportTable">
                <el-table-column
                        label="序号"
                        width="80"
                        align="center">
                    <template v-slot="scope">
                        {{scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column
                        label="学号"
                        prop="userId"
                        width="200"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        prop="realName"
                        width="200"
                        align="center">
                    <template v-slot="scope">
                        <el-tooltip content="查看学生答案和修改分数" placement="top">
                            <span class="col2-cell-style"
                                  @click="reviewStuPaper(scope.$index)">{{scope.row.realName}}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column
                        label="成绩"
                        prop="score"
                        width="150"
                        align="center">
                </el-table-column>

                <el-table-column
                        label="提交次数"
                        prop="submitTimes"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="提交时间"
                        prop="submitTime"
                        width="250"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="status"
                        label="状态"
                        width="150"
                        align="center">
                    <template v-slot="scope">
                        <el-tooltip content="学生未提交作业" placement="top">
                            <el-tag v-if="scope.row.submitTimes == 0" disable-transitions>未提交</el-tag>
                        </el-tooltip>
                        <el-tooltip content="学生已提交作业" placement="top">
                            <el-tag v-if="scope.row.submitTimes > 0" type="success" disable-transitions>已提交</el-tag>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="400">
                    <template v-slot="scope">
                        <el-button
                                size="small"
                                type="info"
                                v-if="scope.row.status == 3">重新阅卷
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!--分页-->
            <Pagination :currentPage="stuCurPage" :pageSize="stuPageSize"
                        :total="stuTotal" :handleSizeChange="handleSizeChange2"
                        :handleCurrentChange="handleCurrentChange2"></Pagination>

        </el-dialog>


        <!--布置作业-->
        <el-dialog title="添加题目" v-model="toAddQuestion" top="1vh" width="80%">
            <template #title>
                <span>选择题目</span>
            </template>

            <!--添加题目 过滤栏-->
            <div class="filter-bar">
                <el-row :span="24">
                    <el-col :span="6">
                        <el-select v-model="categValue" placeholder="请选择题目类型" class="filter-item" clearable filterable
                                @change="problemTypeSearch">
                            <el-option
                                    v-for="item in categOptions.data"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.label"
                            >
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="8">
                        <el-input
                                placeholder="请输入关键词"
                                v-model="questKeyInput"
                                clearable
                                class="filter-item"
                                style="margin-left: 10px;">
                        </el-input>
                        <el-button type="primary" class="filter-item" @click="searchProblemsByKey">
                            <i class="el-icon-search"></i> 搜索
                        </el-button>
                        <el-button type="primary" class="filter-item" @click="reset"><i class="el-icon-refresh"></i>
                            刷新
                        </el-button>
                    </el-col>

                </el-row>
            </div>

            <!--题目表格-->
            <el-table
                    :data="listData.data"
                    style="width: 100%"
                    id="problem-table"
                    >
                <el-table-column
                        label="#"
                        width="80"
                        align="center">
                    <template v-slot="scope">
                        {{scope.$index + 1}}
                    </template>
                </el-table-column>
                <el-table-column
                        label="题目"
                        prop="problemName"
                        width="250">
                </el-table-column>
                <el-table-column
                        label="类型"
                        prop="problemCategories"
                        align="center"
                        width="250">
                </el-table-column>
                <el-table-column
                  prop="problemTags"
                  label="难易"
                  width="150"
                  >
                  <template #default="scope">
                    <el-tag
                    :type="tagColor(scope.row.problemTags)"
                    disable-transitions
                    >{{ scope.row.problemTags }}</el-tag
                    >
                </template>
                </el-table-column>
                <el-table-column label="操作" width="250">
                    <template v-slot="scope">
                        <el-button
                                size="default"
                                type="success"
                                @click="addQuestion(scope.$index)">发布
                        </el-button>
                        <el-button
                                size="default"
                                type="warning"
                                @click="viewProblemDetail(scope.row.problemId)">查看详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页-->
            <Pagination :currentPage="questCurPage" :pageSize="questPageSize"
                        :total="questTotal" :handleSizeChange="handleSizeChange3"
                        :handleCurrentChange="handleCurrentChange3"></Pagination>
        </el-dialog>

        <!--查看题目详情 对话框-->
        <el-dialog title="查看题目详情" v-model="toViewProblemDetail" top="2vh" width="60%">
            <!--题目详情-->
            <div>
                <perfect-scrollbar class="problemDetailTab">
                        <div>
                            <v-md-preview :text="text" preview-class="vuepress-markdown-body" ></v-md-preview>
                        </div>
                    </perfect-scrollbar>
            </div>

            <template #footer>
                <el-button type="primary" @click="toViewProblemDetail = false">关闭</el-button>
            </template>
        </el-dialog>
        <!-- 创建作业对话框 -->
        <el-dialog title="布置作业" v-model ="toCreateHomework">
            <el-form ref="homeworkForm.data" :model="homeworkForm.data" status-icon :rules="homeworkRules">
                <el-form-item label="作业名称" :label-width="formLabelWidth" prop="name" style="width: 90%">
                    <span>&nbsp;{{ homeworkForm.data.name }}&nbsp;&nbsp;&nbsp;</span>
                </el-form-item>
                <el-form-item label="班级名称" :label-width="formLabelWidth" prop="tclass">
                    <span>&nbsp;{{ homeworkForm.data.tclass }}&nbsp;&nbsp;&nbsp;</span>
                </el-form-item>
                <el-form-item label="起止时间" :label-width="formLabelWidth" prop="dateTime">
                    <el-date-picker
                            v-model="homeworkForm.data.dateTime"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="选择语言" :label-width="formLabelWidth" style="width: 90%">
                    <div class="filter-bar">
                        <el-select
                                v-model="homeWorklanguage"
                                multiple
                                collapse-tags
                                collapse-tags-tooltip
                                :max-collapse-tags="3"
                                placeholder="Select"
                                style="width: 240px"
                                >
                                <el-option
                                v-for="item in languageOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                />
                        </el-select>
                    </div>
                </el-form-item>

                <el-form-item label="创建人" :label-width="formLabelWidth" prop="teacher" style="width: 90%">
                    <span>&nbsp;{{ homeworkForm.data.teacher }}&nbsp;&nbsp;&nbsp;</span>

                </el-form-item>
                <el-form-item label="提交次数" :label-width="formLabelWidth"  style="width: 90%">
                    <el-input
                                    placeholder="请输入提交次数，默认为10"
                                    v-model="HomeworkCommitTimes"
                                    clearable
                                    class="filter-item"
                                    style="margin-left: 10px;">
                </el-input>
                </el-form-item>

            </el-form>


            <template #footer>
                <el-button @click="toCreateHomework = false, clearHomeworkForm()">取 消</el-button>
                <el-button type="primary" @click="createHomework()">创 建</el-button>
            </template>
        </el-dialog>
        <!--查阅试卷 对话框-->
        <el-dialog title="" v-model ="toReviewStuPaper" top="2vh" width="80%" v-if="toReviewStuPaper">
            <div class="stu-paper-container">
                <div class="stu-paper-header">
                    <h1>{{ homeworkTitle }}</h1>
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <h3>学号：{{studentDetail.data[curStuIndex].userId}}</h3>
                        </el-col>
                        <el-col :span="6">
                            <h3>姓名：{{studentDetail.data[curStuIndex].realName}}</h3>
                        </el-col>
                        <el-col :span="6">
                            <h3>提交次数：{{studentDetail.data[curStuIndex].submitTimes}}</h3>
                        </el-col>
                        <el-col :span="6">
                            <h3 v-if="studentDetail.data[curStuIndex].score !=0">得分：{{studentDetail.data[curStuIndex].score}}</h3>
                            <h3 v-else>得分：{{0}}</h3>
                        </el-col>
                    </el-row>
                </div>
                <div class="stu-paper-content">
                    <h2>第 1 题
                        <el-input-number style="float: right" size="mini" v-model="nowScore"
                                         :min="0"
                                         :max="100" label="分数"
                                         :disabled="studentDetail.data[curStuIndex].submitTimes == 0"></el-input-number>
                    </h2>
                    <h4 style="clear: both">【题目描述】</h4>
                    <div>
                    <perfect-scrollbar class="problemDetailTab">
                                <div>
                                    <v-md-preview :text="text" preview-class="vuepress-markdown-body" ></v-md-preview>
                                </div>
                            </perfect-scrollbar>
                    </div>
                    <h4>【学生答案】</h4>
                    <div class="stu-answer" v-highlight>
                        <pre>
                            <code v-if="StudentAnswer!=null" :class="languageName">{{StudentAnswer}}</code>
                        </pre>
                    </div>
                </div>

                <div class="stu-paper-footer">
                    <el-button v-if="studentDetail.data[curStuIndex].submitTimes > 0"
                               @click="toReviewStuPaper = false">取 消
                    </el-button>
                    <el-button v-if="studentDetail.data[curStuIndex].submitTimes > 0"
                               type="primary" @click="uploadScore">提交分数
                    </el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog title="克隆作业" v-model="toViewCloneHomeworkPage"  @closed="handleDialogClose">
            <el-row>
                <el-col :span="8">
                    <el-select v-model="cloneClassId" placeholder="克隆前的作业班级名称" class="filter-item" clearable filterable
                               @change="findHomeworkByCloneClassId()">
                        <el-option
                                v-for="item in allTClasses.data"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="8">
                    <el-input v-model="addCloneDays" placeholder="克隆作业增加的天数">
                    </el-input>
                </el-col>

                <el-col :span="2">
                    <el-button @click="modifyCloneHomeworkTime()" type="success">
                        原作业时间顺延天数
                    </el-button>
                </el-col>
            </el-row>

            <el-table :data="cloneSourceProblem.data"
                      @selection-change="handleSelectCloneProblem"
                      ref="multipleTable">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column property="id" label="作业id" width="100" align="center"></el-table-column>
                <el-table-column property="title" label="题目名称" width="220"></el-table-column>
                <el-table-column property="language" label="语言" width="120"></el-table-column>
                <el-table-column property="beginTime" label="开始时间" width="220" align="center"></el-table-column>
                <el-table-column property="endTime" label="结束时间" width="200" align="center"></el-table-column>
            </el-table>
            <br>
            <br>
            <el-row>
                <el-col :span="8">
                    <el-input v-model="cloneHomeworkForm.teacher" :disabled="true">
                    </el-input>
                </el-col>
            </el-row>
            <template #footer>
                <el-button type="primary" @click="cloneHomework()" :disabled="isClone">克 隆</el-button>
                <el-button @click="toViewCloneHomeworkPage = false">取 消</el-button>
            </template>
        </el-dialog>

</template>

<script setup>

import Pagination from "@/components/Pagination.vue"
import { reactive,ref,onMounted } from "vue"
import API from "@/api/trainer/trainerClass"
import { configProviderProps, ElMessage,ElMessageBox  } from 'element-plus'
  components:{Pagination}
onMounted(() => {
    requestTclass()//请求班
    updateList()//请求题库
    requestProblemType()//请求题目类型
    localStorage.setItem('teacherName', '刘新')
})
//克隆
const  cloneHomeworkForm = reactive(
    {
    homeworkName: '',
    tclass: '',
    dateTime: '',
    teacher: localStorage.getItem("loginusername")})
const cloneSelectProblemList = reactive({data:[]})
const toViewCloneHomeworkPage = ref(false)
const cloneClassId = ref('')
//获取选中变化事件
function handleSelectCloneProblem(val) {
    cloneSelectProblemList.data = val;
    console.log(cloneSelectProblemList.data)
}


const allTClasses = reactive({data:{}})
const addCloneDays = ref('')
const homeworkRules = {
                    dateTime: [
                        {required: true, message: '请选择日期', trigger: 'blur'}
                    ],
                }
//用于评判时的语言
const languageName = ref('')
const StudentAnswer  = ref('')
function getThisDate(originalDateTime){

      const date = new Date(originalDateTime);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      let formattedDateTime = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
    return formattedDateTime
}
//   获取时间
  const date = new Date()
  const formLabelWidth = ref('120px')
  const language = ref('C')//修改作业时间时候用的语言

//   主界面翻页
  const tclassDetail = reactive(
    {data:[]})
  const currentPage = ref(1)
  const pageSize = ref(20)
  const total = ref(0)

//
  const tclassInput = ref('')
  const curClassIndex = ref(0) //查看教学班的班级序号
  const curStuIndex = ref(0) //查看学生的学生序号

  const curProblemIndex = ref(0) //创建作业的题目序号
  const currentClassId =ref(-1) //现在查看的班级号
  const toViewHomeworkByClass =ref(false)//是否查看班级布置的作业弹窗
  const toViewHomeworkDetail = ref(false)//是否查看作业提交情况弹窗
// 布置作业弹窗
  let qLib = reactive({data:[]})//题库
  const categValue = ref('')//类型选择框
  const currCatevalue = ref(0)//现在的选中类型值
  const questKeyInput = ref('')//搜索输入框
  //翻页
  const questCurPage = ref(1) // 题库当前页码
  const questPageSize= ref(20) // 题库每页条目个数
  const questTotal = ref(0) //题库题目总数
  const categoryId = ref(0) //题库公司id
  const tagId = ref(0) //题库难度
  function handleSizeChange3(val) {
                questPageSize.value = val;
                updateList()
            }
  function  handleCurrentChange3(val) {
                questCurPage.value = val;
                updateList()
            }
  let categOptions = reactive(
            {
                data:[{
                    value: '选项0',
                    label: '图论',
                }, {
                    value: '选项1',
                    label: '动态规划',
                }, {
                    value: '选项2',
                    label: '基础编程',
                }]
                })
  //获取题库的题目类型
  function requestProblemType(){
      categOptions.data = [];
      API.getCategories().then(res=>{
        console.log(res)
        for (let i = 0; i < res.data.content.length; i++) {
            let map = {};
            map.value = res.data.content[i].problemCategoryId;
            map.label = res.data.content[i].problemCategoryName;
            categOptions.data.push(map);
        }
            }).catch(e=>{
            console.log(e)
            ElMessage.success("请求类型失败")
            })

  }
  //获取选项框的值
  function problemTypeSearch(){
      for(let i = 0;i<categOptions.data.length;i++){
          if(categValue.value == categOptions.data[i].label){
            currCatevalue.value = categOptions.data[i].value
            console.log(currCatevalue.value)
            break
          }
      }
        let param = {}
        param.size =  questPageSize.value
        param.current = questCurPage.value
        param.categoryId = currCatevalue.value
        if(tagId.value!=0){
        param.tagId =  tagId.value
        }
        API.questionList(param).then(res=>{
        listData.data = res.data.content.records
        questTotal.value = res.data.content.total
        }).catch(e=>{
        console.log(e)
        })

  }
  const listData = reactive({data:[]})
  function updateList() {
          let param = {}
          param.size = questPageSize.value
          param.current = questCurPage.value
          if(currCatevalue.value!==0){
            param.categoryId = currCatevalue.value
          }
          if(tagId.value!==0){
            param.tagId = tagId.value
          }
          API.questionList(param).then(res=>{
            console.log(res)
            listData.data = res.data.content.records
            questTotal.value = res.data.content.total
          }).catch(e=>{
            console.log(e)
          })

            }
  //搜索题目
  function searchProblemsByKey(){
          let param = {}
          param.size = 20
          param.current = 1
          categoryId.value = 0
          tagId.value = 0
          questCurPage.value = 1
          questPageSize.value = 20
          param.keyword= questKeyInput.value
          if(currCatevalue.value!==0){
            param.categoryId = currCatevalue.value
          }
          if(tagId.value!==0){
            param.tagId = tagId.value
          }
          API.questionList(param).then(res=>{
            listData.data = res.data.content.records
            questTotal.value = res.data.content.total
          }).catch(e=>{
            console.log(e)
          })
        }
  //重置题目的搜索
  function reset(){
          questKeyInput.value =''
          let param = {}
          param.size = 20
          param.current = 1
          currCatevalue.value = 0
          questCurPage.value = 1
          questPageSize.value = 20
          tagId.value = 0
          let token = localStorage.getItem('token')
          API.questionList(param,token).then(res=>{
            listData.data = res.data.content.records
            totalCount.value = res.data.content.total
          }).catch(e=>{
            console.log(e)
          })
        }

  const toAddQuestion = ref(false)
  function assignHomework(index) {
                toAddQuestion.value = true;
                curClassIndex.value = index;
                currentClassId.value = tclassDetail.data[index].id
                // Lib = qLib;
                categValue.value = '';
                questKeyInput.value = '';
            }

// 作业详情弹窗
const toViewProblemDetail = ref(false)
let problemDetail = reactive({data:[]})
const curCheckpoints = reactive({data:[]})
const standardAnswerLanguage = ref('')
const standardAnswer = ref('管理员尚未发布标准答案...')
//查看题目详情
function viewProblemDetail(index) {
                curProblemIndex.value = index;
                console.log(curProblemIndex.value)
                problemDetail.data = listData.data[index];
                let detail ={}
                detail.id = index
                API.questionDetail(detail).then(res=>{
                    localStorage.setItem("CURRENT_PROBLEM",JSON.stringify(res.data.content))
                    problemDetail.data = res.data.content
                    //这里必需写在请求体内因为函数会晚执行
                    problemFormatToMarkdown()
                    toViewProblemDetail.value = true;
                }).catch(e=>{
                    console.log(e)
                })


            }
//查看作业详情的题目
const curHomeworkProblemIndex = ref(0)
const HomeworkproblemDetail = reactive({data:[]})
function viewHomeworkProblemDetail(index) {
                console.log(index)
                let detail ={}
                detail.id = index
                API.questionDetail(detail).then(res=>{
                    console.log(res.data)
                    localStorage.setItem("CURRENT_PROBLEM",JSON.stringify(res.data.content))
                    problemDetail.data = res.data.content
                    //这里必需写在请求体内因为函数会晚执行
                    problemFormatToMarkdown()
                }).catch(e=>{
                    console.log(e)
                })


            }
// 添加作业弹窗
const toCreateHomework = ref(false)
const homeWorklanguage = ref([])
const languageOptions = [
                    {
                        value: '1',
                        label: 'C',
                    },
                    {
                        value: '2',
                        label: 'C++',
                    },
                    {
                        value: '3',
                        label: 'JAVA',
                    },
                    // {
                    //     value: '4',
                    //     label: 'PASCAL',
                    // },
                    {
                        value: '5',
                        label: 'PYTHON3',
                    },
                    // {
                    //     value: '6',
                    //     label: 'RUBY',
                    // },
                    ]
//   查看已布置作业
  const HomeworkCurrPage = ref(1)
  const HomeworkPageSize = ref(10)
  const HomeworkTotal = ref(0)
  function handleSizeChange4(val){
    HomeworkPageSize.value = val
    viewHomeworkByClass(curClassIndex.value)
  }
  function handleCurrentChange4(val){
    HomeworkCurrPage.value = val
    viewHomeworkByClass(curClassIndex.value)
  }

  function viewHomeworkByClass(index) {
                curClassIndex.value = index;
                tclassHomeworkDetail.data = []
                currentClassId.value = tclassDetail.data[index].id;
                let getHomeworkParams = {
                    pageNumber : HomeworkCurrPage.value,
                    pageSize : HomeworkPageSize.value,
                    trainClassId : currentClassId.value
                }
                API.getHomework(getHomeworkParams).then(res=>{
                        if(res.data.success==true){
                                console.log(res.data)
                                HomeworkTotal.value = res.data.content.total
                                //另一个API
                                let isWoring  = true
                                if(res.data.content.records && res.data.content.records[0]){
                                    for(let i = 0;i<res.data.content.records.length;i++)
                                                {
                                                            tclassHomeworkDetail.data[i] = res.data.content.records[i]
                                                            const date1 = new Date();
                                                            const date2 = new Date(tclassHomeworkDetail.data[i].endTime);
                                                            if(date1>date2){

                                                                tclassHomeworkDetail.data[i].status = 0
                                                            }
                                                            tclassHomeworkDetail.data[i].beginTime = getThisDate(tclassHomeworkDetail.data[i].beginTime)
                                                            tclassHomeworkDetail.data[i].endTime = getThisDate(tclassHomeworkDetail.data[i].endTime)
                                                            



                                                }
                                                if(isWoring){

                                                    ElMessage.success('请求作业成功')
                                                }
                                                else{
                                                    ElMessage.error('请求作业失败')
                                                }
                                }
                                else{
                                    tclassHomeworkDetail.data = []
                                    ElMessage.success("请求作业成功")
                                }

                        }else {
                        console.log(res.data)
                        ElMessage.error("获取作业失败，请联系管理员")
                        }
                }).catch(error=>{
                        console.log(error)
                    })
                toViewHomeworkByClass.value = true;
            }
// 弹窗关闭触发
  function closeHomeworkDialog(){
    tclassHomeworkDetail.data = []
  }
//评分的分数
const nowScore = ref(0)
// 删除作业
const toDeleteHomework = ref(false)
  function deleteHomework(index){

    let deleteHomeworkparams ={
        trainClassId : tclassDetail.data[curClassIndex.value].id,
        homeworkId : tclassHomeworkDetail.data[index].id
    }
    console.log(deleteHomeworkparams)
    API.deleteHomework(deleteHomeworkparams).then(res=>{
            if(res.data.success==true){
            console.log(res.data)
            ElMessage.success("删除作业成功")
            toDeleteHomework.value = false
            viewHomeworkByClass(curClassIndex.value)
            }else {
            console.log(res.data)
            ElMessage.error("删除作业失败，请联系管理员"+`${res.data.message}`)
            }
            // this.classTable=res.data
        }).catch(error=>{
                console.log(error)
            })

  }
//   修改已布置的作业时间
  let homeworkForm = reactive({data:{
                    name: '',
                    tclass: '',
                    dateTime: '',
                    teacher: localStorage.getItem("teacherName"),
  }})//修改的表格
  const toChangeHomeworkTime = ref(false)//修改作业结束时间弹窗
  function changeHomeworkTime(index) {
                clearHomeworkForm();
                curHomeworkIndex.value = index;
                toChangeHomeworkTime.value = true;
                homeworkForm.data.teacher = "px";
                homeworkForm.data.dateTime = [tclassHomeworkDetail.data[index].beginTime,
                tclassHomeworkDetail.data[index].endTime];
                homeworkForm.data.tclass = tclassDetail.data[curClassIndex.value].name;
                homeworkForm.data.name = tclassHomeworkDetail.data[index].title;
                language.value = tclassHomeworkDetail.data[index].language;

                console.log(homeworkForm.data)
            }
  function clearHomeworkForm() {
                homeworkForm.data = {
                    name: '',
                    tclass: '',
                    dateTime: '',
                    teacher: localStorage.getItem("teacherName"),
                }
                homeWorklanguage.value = []
                HomeworkCommitTimes.value = 10
            }
  function changeHomeworkTimeComfirm(){
    
    if(homeworkForm.data.dateTime[0]==tclassHomeworkDetail.data[curHomeworkIndex.value].beginTime){
        ElMessage.error("请输入时间")
        return
    }
    if(homeWorklanguage.value.length==0){
        ElMessage.error("请选择语言")
        return
    }

    let beginTime = formatdate(new Date(homeworkForm.data.dateTime[0]).toLocaleString())
    let endTime = formatdate(new Date(homeworkForm.data.dateTime[1]).toLocaleString())
    console.log("xxx")
    let nowLanguage = ''
    for(let i =0;i< homeWorklanguage.value.length;i++){
        nowLanguage = nowLanguage + homeWorklanguage.value[i] +','
    }
    nowLanguage = nowLanguage.slice(0, -1)
    let updateHomeworkParams = {
        "homeworkId": tclassHomeworkDetail.data[curHomeworkIndex.value].id,
        "title": tclassHomeworkDetail.data[curHomeworkIndex.value].title,
        "totalScore": 100,
        "language": nowLanguage,
        "beginTime": beginTime,
        "endTime": endTime
    }
    console.log(updateHomeworkParams)
    API.updateHomework(updateHomeworkParams).then(res=>{
                    if(res.data.success==true){
                    console.log(res.data)
                    ElMessage.success("修改班级作业详情成功")
                    viewHomeworkByClass(curClassIndex.value)
                    }else {
                    console.log(res.data)
                    ElMessage.error("修改班级作业详情失败，请联系管理员")
                    }
                }).catch(error=>{
                        console.log(error)
                    })
    clearHomeworkForm()
    toChangeHomeworkTime.value = false;
  }
  const HomeworkCommitTimes = ref(10)
  //将2024/5/6 00:00:00这个字符串转成2024-05-06T20:00:00.000+0000这种格式
  function formatdate(time){
    let dateString = time;

    // 将斜杠替换为连字符，方便后续转换
    dateString = dateString.replace(/\//g, '-');

    // 创建日期对象
    let dateObject = new Date(dateString);

    // 获取 ISO 8601 格式的日期字符串
    let isoDateString = dateObject.toISOString();

    // 手动调整时区偏移量
    let adjustedDateString = isoDateString.replace('Z', '+0000');

    return adjustedDateString;
  }
  function clearForm() {
                tclassForm = {
                    name: '',
                    nclass: [],
                    endTime: '',
                    teacher: localStorage.getItem("teacherName"),
                }
            }

//   查看已布置作业弹窗

  const tclassHomeworkDetail = reactive({data:[]})

  const selectedProblemList = reactive({data:[]})
  function handleSelectionChange(val) {
        selectedProblemList.data = val;
        console.log(selectedProblemList.data)
    }
    // 查看学生的作业情况
    const studentDetail = reactive({data:[]}) //学生表格数据
    const hwStudents = reactive([])  //某个作业的所有学生及其提交情况
    const homeworkTitle = ref('')//标题（作业名字）
    const curHomeworkIndex = ref(0) //查看作业的作业序号
    const eidInput = ref('')
    // 提交学生表翻页
    const stuCurPage = ref(1)
    const stuPageSize =ref(20)
    const stuTotal = ref(0)
    function handleSizeChange2(val) {
                stuPageSize.value = val;
            }
    function handleCurrentChange2(val) {
                stuCurPage.value = val;
            }
// 查看班级的具体作业提交
    const currHomeworkId = ref(0)//现在的作业号
    function viewStudentByHomework(index) {
                console.log('curHomeworkIndex',curHomeworkIndex.value)
                console.log(index)
                console.log(tclassHomeworkDetail.data[index].id)
                homeworkTitle.value = tclassHomeworkDetail.data[index].title;
                currHomeworkId.value = tclassHomeworkDetail.data[index].id
                curHomeworkIndex.value = index;
                stuCurPage.value = 1;
                toViewHomeworkDetail.value = true
                studentDetail.data = [];
                let currclass = currentClassId.value
                let getHomeworkSubmissionParams = {
                    "pageNumber": stuCurPage.value,
                    "pageSize": stuPageSize.value,
                    "trainClassId": currclass,
                    "homeworkId": tclassHomeworkDetail.data[index].id
                }
                console.log("getHomeworkSubmissionParams",getHomeworkSubmissionParams)


                API.getHomeworkSubmission(getHomeworkSubmissionParams).then(res=>{
                    if(res.data.success==true){
                    console.log(res.data)
                    studentDetail.data = res.data.content.records

                    for(let i= 0;i<studentDetail.data.length;i++)
                    {
                       if(studentDetail.data[i].score == null)
                       {
                        studentDetail.data[i].score = 0
                       }


                    }
                    stuTotal.value = res.data.content.total
                    toViewHomeworkDetail.value = true;
                    ElMessage.success("请求班级作业详情成功")
                    }else {
                    console.log(res.data)
                    ElMessage.error("请求班级作业详情失败，请联系管理员")
                    }
                }).catch(e=>{
                console.log(e)
                })

    }
    const toReviewStuPaper = ref(false)
    function reviewStuPaper(index){
        console.log(studentDetail.data[index])
        curStuIndex.value = index
        toReviewStuPaper.value = true
        nowScore.value = studentDetail.data[index].score
        StudentAnswer.value = ''
        if(studentDetail.data[curStuIndex.value].lastSubmitId != null){
            let getNowSubParams = {
            size: 10,
            current: 1,
            submissionId: studentDetail.data[curStuIndex.value].lastSubmitId
            }
            StudentAnswer.value = null
            API.getNowSub(getNowSubParams).then(res=>{
                        console.log(res.data.content.records[0])
                        languageName.value = res.data.content.records[0].languageName
                        StudentAnswer.value =  res.data.content.records[0].submissionCode
                    }).catch(e=>{
                        console.log(e)
                    })
        }

        viewHomeworkProblemDetail(studentDetail.data[index].problemId)
    }
    //请求班级
    function requestTclass(){
        let getTrainClassparams = {
                "pageNumber": currentPage.value,
                "pageSize": pageSize.value,
            }

            API.getTrainClass(getTrainClassparams).then(res=>{
            if(res.data.success==true){
            console.log(res.data)
            ElMessage.success("请求班级成功")
            tclassDetail.data = res.data.content.list
            for(let i = 0;i<tclassDetail.data.length;i++){

                // 创建一个新的 Date 对象，将 UTC 时间字符串作为参数传入
                let utcDate = new Date(tclassDetail.data[i].createTime);

                // 设置目标时区偏移量为 UTC-16 时区偏移量
                let offset = +16 * 60; // -16小时 * 60分钟
                let targetDate = new Date(utcDate.getTime() + (offset * 60000));

                // 获取目标时区的年、月、日、时、分
                let year = targetDate.getUTCFullYear();
                let month = (targetDate.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
                let day = targetDate.getUTCDate().toString().padStart(2, '0');
                let hours = targetDate.getUTCHours().toString().padStart(2, '0');
                let minutes = targetDate.getUTCMinutes().toString().padStart(2, '0');

                // 构建目标时区的字符串格式（例如：2024-05-05日 14:57）
                let targetDateTimeString = `${year}-${month}-${day}日 ${hours}:${minutes}`;
                tclassDetail.data[i].createTime = targetDateTimeString
                tclassDetail.data[i].teacherName = localStorage.getItem("loginusername")
                }
            for(let i = 0;i<tclassDetail.data.length;i++){

            // 创建一个新的 Date 对象，将 UTC 时间字符串作为参数传入
            let utcDate = new Date(tclassDetail.data[i].updateTime);

            // 设置目标时区偏移量为 UTC-16 时区偏移量
            let offset = +16 * 60; // -16小时 * 60分钟
            let targetDate = new Date(utcDate.getTime() + (offset * 60000));

            // 获取目标时区的年、月、日、时、分
            let year = targetDate.getUTCFullYear();
            let month = (targetDate.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
            let day = targetDate.getUTCDate().toString().padStart(2, '0');
            let hours = targetDate.getUTCHours().toString().padStart(2, '0');
            let minutes = targetDate.getUTCMinutes().toString().padStart(2, '0');

            // 构建目标时区的字符串格式（例如：2024-05-05日 14:57）
            let targetDateTimeString = `${year}-${month}-${day}日 ${hours}:${minutes}`;
            tclassDetail.data[i].updateTime = targetDateTimeString
            }
            total.value = res.data.content.total
            let maxp = total.value/pageSize.value
            if(total.value%pageSize.value != 0){
                maxp++
            }
            if(currentPage.value>maxp && currentPage.value > 1){
                currentPage.value = 1
                getTrainClass()
            }
            allTClasses.data = tclassDetail.data
            }else {
            console.log(res.data)
            ElMessage.error("请求班级失败，请联系管理员")
            }
            // this.classTable=res.data
        }).catch((err) => {
                    console.log(err);
        })
    }
//题目详情界面
const text = ref('Initialize Failed...')
let nowcurrentProblem = {}
const CreateHomeworkId = ref(0)
function problemFormatToMarkdown() {

let currentProblem = localStorage.getItem("CURRENT_PROBLEM")
if (currentProblem === undefined || currentProblem == "") {
    return;
}

nowcurrentProblem =  JSON.parse(currentProblem)
console.log(nowcurrentProblem)
let problemDescriptionString = [

    "# 题目名称" + "\n\n" + "**" + nowcurrentProblem.problemId + "**" + " ：" + nowcurrentProblem.problemName + "(" + nowcurrentProblem.problemCategories + ")\n\n",
    "## 题目描述" + "\n\n" + nowcurrentProblem.description + "\n\n",
    "## 提示" + "\n\n" + nowcurrentProblem.hint + "\n\n",
    "### 输入输出格式" + "\n\n",


    "::: tip <font style='color: red'>输入格式</font>\n" +
    nowcurrentProblem.inputFormat +
    "\n:::\n",

    ":::  tip <font style='color: red'>输出格式</font>\n" +
    nowcurrentProblem.outputFormat +
    "\n:::\n",


    "### 输入输出样例" + "\n\n",


    ":::  tip <font color=\"#dd0000\">输入</font>\n" +
    nowcurrentProblem.sampleInput +
    "\n:::\n",

    ":::  tip <font color=\"#dd0000\">输出</font>\n" +
    nowcurrentProblem.sampleOutput +
    "\n:::\n",


    ":::  tip <font color=\"#dd0000\">时间限制</font>\n" +
    nowcurrentProblem.timeLimit + "ms" +
    "\n:::\n",

    "::: tip <font color=\"#dd0000\">内存限制</font>\n" +
    nowcurrentProblem.memoryLimit + "KB" +
    "\n:::\n",
];
 text.value = problemDescriptionString.join("");

}
function downloadExcelBySelectedProblemId(){
    if (selectedProblemList.data.length == 0) {
                    ElMessage.error("请选择至少一个题目导出学生成绩");
                    return;
            }
                let selectedProblemIdList = [];
                for (let i = 0; i < selectedProblemList.data.length; i++) {
                    selectedProblemIdList.push(selectedProblemList.data[i].id);
                }
                console.log("downloadExcel",selectedProblemIdList);
                let downloadGradeparams = {
                        homeworkId : selectedProblemIdList+'',
                        classId : tclassDetail.data[curClassIndex.value].id
                    }
                API.downloadGrade(downloadGradeparams,{responseType: 'blob'}).then(res=>{
                    console.log(res)
                    const blog = new Blob([res.data],{
                        type: 'application/vnd.ms-excel'
                    });
                    const aLink = document.createElement('a');
                    aLink.style.display = 'none';
                    const url = window.URL.createObjectURL(blog);
                    console.log(url)
                    aLink.href = window.URL.createObjectURL(blog);
                    aLink.download = `${tclassDetail.data[curClassIndex.value].name}.xls`;
                    document.body.appendChild(aLink);
                    aLink.click();
                    document.body.removeChild(aLink);
                    }).catch(e=>{
                    console.log(e)
                        })
                return false;
}
function addQuestion(index){
    curProblemIndex.value = index;
    let homeworkNow = listData.data[curProblemIndex.value]
    homeworkForm.data.problemId = homeworkNow.problemId
    homeworkForm.data.name =  homeworkNow.problemName;
    homeworkForm.data.tclass = tclassDetail.data[curClassIndex.value].name;
    homeworkForm.data.dateTime = '';
    homeworkForm.data.teacher = localStorage.getItem("teacherName");
    homeworkForm.data.dateTime = [new Date(), new Date()]
    toCreateHomework.value = true

}
//查重报告，下载重复率检测报告
function downloadRepCheckReport() {
    console.log(tclassDetail.data[curClassIndex.value].id)
    let downloadChachongparams = {
        classId: tclassDetail.data[curClassIndex.value].id,
        homeworkId: tclassHomeworkDetail.data[curHomeworkIndex.value].id
    }
    API.downloadChachong(downloadChachongparams,{responseType: 'blob'}).then(res=>{
                    
                    console.log(res)
                    const blog = new Blob([res.data],{
                        type: 'application/vnd.ms-excel'
                    });
                    const aLink = document.createElement('a');
                    aLink.style.display = 'none';
                    const url = window.URL.createObjectURL(blog);
                    console.log(url)
                    aLink.href = window.URL.createObjectURL(blog);
                    aLink.download = `${tclassDetail.data[curClassIndex.value].name}.xls`;
                    document.body.appendChild(aLink);
                    aLink.click();
                    document.body.removeChild(aLink);
                    }).catch(e=>{
                    console.log(e)
                        })
}
//用于存储克隆的题目
const cloneSourceProblem = reactive({data:[]})
const oldCloneSourceProblem = reactive({data:[]})
const oldDataNoformatbegintime  = reactive([])
const oldDataNoformatendtime  = reactive([])
const oldDataNoformatLanguage  = reactive([])
const isClone = ref(false)
//转型语言
const languageMap ={
    '1': 'C',
    '2': 'C++',
    '3': 'JAVA',
    // '4': 'PASCAL',
    '5': 'PYTHON3',
    // '6': 'RUBY'
}
//用classid找到布置的作业
function findHomeworkByCloneClassId(){
    cloneSourceProblem.data = []
    let getAllClassHomeworkparams = {
        classId: cloneClassId.value
    }
    API.getAllClassHomework(getAllClassHomeworkparams).then(res=>{
                    console.log(res.data)
                    cloneSourceProblem.data = res.data.content
                    for(let i = 0;i< cloneSourceProblem.data.length; i++)
                    {   //时间转型   及存储
                        oldDataNoformatbegintime[i] = cloneSourceProblem.data[i].beginTime

                        cloneSourceProblem.data[i].beginTime = getThisDate(cloneSourceProblem.data[i].beginTime)
                        oldDataNoformatendtime[i] = cloneSourceProblem.data[i].endTime

                        cloneSourceProblem.data[i].endTime = getThisDate(cloneSourceProblem.data[i].endTime)
                        //转型语言
                        oldDataNoformatLanguage[i] = cloneSourceProblem.data[i].language

                        let languagesArr= cloneSourceProblem.data[i].language.split(',')
                        let newlanguage = ''
                        languagesArr.forEach(item=>{
                            newlanguage = newlanguage + languageMap[item] +','
                        })
                        console.log(newlanguage)
                        cloneSourceProblem.data[i].language = newlanguage

                    }
                    oldCloneSourceProblem.data = deepCopy(cloneSourceProblem.data)
                    }).catch(e=>{
                    console.log(e)
                        })
}
function deepCopy(obj) {
                if (typeof obj !== 'object' || obj === null) {
                    // 如果不是引用类型或者是 null，直接返回
                    return obj;
                }

                let newObj = Array.isArray(obj) ? [] : {};
                for (let key in obj) {
                    if (Object.prototype.hasOwnProperty.call(obj, key)) {
                        newObj[key] = deepCopy(obj[key]);
                    }
                }
                return newObj;
            }
// 判断数字
function isInteger(num) {
    // 使用 parseInt 函数将字符串形式的数字转换为整数，然后将其与原始值比较
    return typeof num === 'number' && isFinite(num) && Math.floor(num) === num;
}
function createHomework(){
    if(homeWorklanguage.value.length==0){
        ElMessage.error("请选择语言")
        return
    }
    const date1 = new Date()
    const date2 = new Date(homeworkForm.data.dateTime[1])
    if(date1>date2){
        ElMessage.error("结束时间应该晚于现在")
        return
    }
    console.log(isInteger(+HomeworkCommitTimes.value))
    if((!isInteger(+HomeworkCommitTimes.value)) || (+HomeworkCommitTimes.value<=0))
    {
        ElMessage.error("提交次数为整数，必须大于0")
        return
    }
     let nowLanguage = ''
    for(let i =0;i< homeWorklanguage.value.length;i++){
        nowLanguage = nowLanguage + homeWorklanguage.value[i] +','
    }
    console.log(nowLanguage)
    nowLanguage = nowLanguage.slice(0, -1)
    let createHomeworkparams = {
            "title": homeworkForm.data.name,
            "totalScore": 100,
            "language": nowLanguage,
            "notes": "",
            "commitTimes": HomeworkCommitTimes.value,
            "questionDetail": [
                {
                "problemId": homeworkForm.data.problemId,
                "score": 100
                }
            ],
            "beginTime": homeworkForm.data.dateTime[0],
            "endTime": homeworkForm.data.dateTime[1]
    }


    let assignHomeworkparams = {}

    API.createHomework(createHomeworkparams).then(res=>{
            if(res.data.success==true){
            console.log(res.data)
            toCreateHomework.value = false
            CreateHomeworkId.value = res.data.content.id
            assignHomeworkparams.homeworkId = CreateHomeworkId.value,
            assignHomeworkparams.trainClassId = currentClassId.value
            //
            API.assignHomework(assignHomeworkparams).then(res=>{
            if(res.data.success==true){
            console.log(res.data)
            ElMessage.success("添加作业成功")
            }else {
            console.log(res.data)
            ElMessage.error("添加作业失败，请联系管理员")
            }
            })
            //
            }else {
            console.log(res.data)
            ElMessage.error("添加作业失败，请联系管理员")
            }
            }).catch(e=>{
                console.log(e)
                })

    console.log("assignHomeworkparams",assignHomeworkparams)
    // 清除表格
    clearHomeworkForm()
}
 
function findContentTypeValue(str) {
  // 匹配 content-type 字段及其对应的值
  const regex = /"content-type"\s*:\s*"([^"]+)"/;

  // 使用正则表达式进行匹配
  const match = str.match(regex);

  // 如果找到匹配项，则返回对应的值，否则返回 null
  if (match && match.length > 1) {
    return match[1];
  } else {
    return null;
  }
}
//下载成绩
function downloadExcel(index){
   console.log(tclassDetail.data[index].id)

   let getAllClassHomeworkparams = {
    classId: tclassDetail.data[index].id
   }
   let classIds = []
   API.getAllClassHomework(getAllClassHomeworkparams).then(res=>{
        for(let i = 0;i < res.data.content.length;i++){
            classIds[i] = res.data.content[i].id
        }
        let downloadGradeparams = {
            homeworkId : classIds+'',
            classId : tclassDetail.data[index].id
        }
        API.downloadGrade(downloadGradeparams).then(res=>{
            console.log(res.headers)
            let isFile = true;
            if(res.headers['content-disposition']!=null){
                isFile =false;
            }
            if(isFile){
                ElMessage.error("该班级还未有提交或者未创建作业")
                return
            }
            const blog = new Blob([res.data],{
                type: 'application/vnd.ms-excel'
            });
            const aLink = document.createElement('a');
            aLink.style.display = 'none';
            const url = window.URL.createObjectURL(blog);
            console.log(url)
            aLink.href = window.URL.createObjectURL(blog);
            aLink.download = `${tclassDetail.data[index].name}.xls`;
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
            }).catch(e=>{
            console.log(e)
        })
        }).catch(e=>{
        console.log(e)
        })
}
function addDay(olddate,day){
    const dateString = olddate;
// 将日期字符串转换为时间戳（毫秒）
const timestamp = Date.parse(dateString);
// 创建 Date 对象并解析为本地时间
const oldDate = new Date(timestamp)
// 添加 n 天
const nDays = day; // 假设要添加的天数
let newTimestamp = timestamp + (nDays * 24 * 60 * 60 * 1000);
const date = new Date(newTimestamp);
const newDateString = date.toISOString();

    return(newDateString); // 输出新的日期字符串
}
//克隆作业
function modifyCloneHomeworkTime() {
                if (isNaN(addCloneDays.value) || addCloneDays.value == '') {
                    ElMessage.error("请输入数字...")
                    return;
                }
                if (cloneSourceProblem.data.length === 0) {
                    ElMessage.error('请选择需要克隆的作业...')
                    return;
                }
                for (let i = 0; i < cloneSourceProblem.data.length; i++) {
                    oldDataNoformatbegintime[i] = addDay(oldDataNoformatbegintime[i],addCloneDays.value)
                    cloneSourceProblem.data[i].beginTime =  getThisDate(oldDataNoformatbegintime[i])
                    oldDataNoformatendtime[i] = addDay(oldDataNoformatendtime[i],addCloneDays.value)
                    cloneSourceProblem.data[i].endTime =  getThisDate(oldDataNoformatendtime[i])
                }
                ElMessage.success("请核对克隆作业时间的变化...")
            }

async function cloneHomework(){
    if (cloneSelectProblemList.data.length == 0) {
                   ElMessage.error("请选择至少一个题目");
                    return;
        }
    let count = 0;
    for(let i = 0; i<cloneSelectProblemList.data.length; i++ ){
        isClone.value = true
        let getHomeworkProblemIdparams = {homeworkId: cloneSelectProblemList.data[i].id}
        let res = await API.getHomeworkProblemId(getHomeworkProblemIdparams).then(res=>{
            let createHomeworkparams = {
                "title": cloneSelectProblemList.data[i].title,
                "totalScore": 100,
                "language": oldDataNoformatLanguage[i],
                "notes": "",
                "commitTimes": 10,
                "questionDetail": [
                    {
                    "problemId": res.data.content[0],
                    "score": 100
                    }
                ],
                "beginTime": oldDataNoformatbegintime[i],
                "endTime": oldDataNoformatendtime[i]
            }
            console.log(createHomeworkparams)
            API.createHomework(createHomeworkparams).then(res=>{
            if(res.data.success==true){
            console.log(res.data)
            let assignHomeworkparams = {
                homeworkId : res.data.content.id,
                trainClassId : tclassDetail.data[curClassIndex.value].id
                }
                console.log(assignHomeworkparams)

            API.assignHomework(assignHomeworkparams).then(res=>{
                if(res.data.success==true){
                console.log(res.data)
                count++
                console.log(count)
                if(count ==cloneSelectProblemList.data.length){
                    ElMessage.success("克隆成功")
                    toViewCloneHomeworkPage.value = false
                    viewHomeworkByClass(curClassIndex.value)
                }
                }else {
                console.log(res.data)
                }
                }).catch(e=>{
                    console.log(e)
                    ElMessage.error("克隆失败")
                })
            //
            }else {
            console.log(res.data)
            }
            }).catch(e=>{
                console.log(e)
                ElMessage.error("克隆失败")
                })
        }).catch(error=>{
        console.log(error)
      })


    }
}
//监视克隆作业弹窗
function handleDialogClose(){
    isClone.value = false;
}
//搜索班级
function searchClass(){
            let getTrainClassparams = {
                "pageNumber": currentPage.value,
                "pageSize": pageSize.value,
                "name": tclassInput.value
            }
            API.getTrainClass(getTrainClassparams).then(res=>{
            if(res.data.success==true){
            console.log(res.data)
            ElMessage.success("请求班级成功")
            tclassDetail.data = res.data.content.list
            total.value = res.data.content.total
            for(let i = 0;i<tclassDetail.data.length;i++){

            // 创建一个新的 Date 对象，将 UTC 时间字符串作为参数传入
            let utcDate = new Date(tclassDetail.data[i].createTime);

            // 设置目标时区偏移量为 UTC-16 时区偏移量
            let offset = +16 * 60; // -16小时 * 60分钟
            let targetDate = new Date(utcDate.getTime() + (offset * 60000));

            // 获取目标时区的年、月、日、时、分
            let year = targetDate.getUTCFullYear();
            let month = (targetDate.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
            let day = targetDate.getUTCDate().toString().padStart(2, '0');
            let hours = targetDate.getUTCHours().toString().padStart(2, '0');
            let minutes = targetDate.getUTCMinutes().toString().padStart(2, '0');

            // 构建目标时区的字符串格式（例如：2024-05-05日 14:57）
            let targetDateTimeString = `${year}-${month}-${day}日 ${hours}:${minutes}`;
            tclassDetail.data[i].createTime = targetDateTimeString
            tclassDetail.data[i].teacherName = localStorage.getItem("loginusername")
            }
            for(let i = 0;i<tclassDetail.data.length;i++){

            // 创建一个新的 Date 对象，将 UTC 时间字符串作为参数传入
            let utcDate = new Date(tclassDetail.data[i].updateTime);

            // 设置目标时区偏移量为 UTC-16 时区偏移量
            let offset = +16 * 60; // -16小时 * 60分钟
            let targetDate = new Date(utcDate.getTime() + (offset * 60000));

            // 获取目标时区的年、月、日、时、分
            let year = targetDate.getUTCFullYear();
            let month = (targetDate.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
            let day = targetDate.getUTCDate().toString().padStart(2, '0');
            let hours = targetDate.getUTCHours().toString().padStart(2, '0');
            let minutes = targetDate.getUTCMinutes().toString().padStart(2, '0');

            // 构建目标时区的字符串格式（例如：2024-05-05日 14:57）
            let targetDateTimeString = `${year}-${month}-${day}日 ${hours}:${minutes}`;
            tclassDetail.data[i].updateTime = targetDateTimeString
            }
            let maxp = total.value/pageSize.value
            if(total.value%pageSize.value != 0){
                maxp++
            }
            if(currentPage.value>maxp && currentPage.value > 1){
                currentPage.value = 1
                getTrainClass()
            }
            }else {
            console.log(res.data)
            ElMessage.error("请求班级失败，请联系管理员")
            }
            // this.classTable=res.data
        }).catch(error=>{
                console.log(error)
            })
        }
//改作业分数
function uploadScore(){
    let sid = studentDetail.data[curStuIndex.value].lastSubmitId
    if(sid == null){
        ElMessage.error("未提交不能评分")
        return
    }
    let scoreHomeworkParams ={
        userId: studentDetail.data[curStuIndex.value].userId ,
        submitId: sid,
        score: nowScore.value
    }
    console.log(scoreHomeworkParams)
    API.scoreHomework(scoreHomeworkParams).then(res=>{
                    if(res.data.success==true){
                    console.log(res.data)
                    ElMessage.success("修改作业成绩成功")
                    viewStudentByHomework(curHomeworkIndex.value)
                    toReviewStuPaper.value = false
                    }else {
                    console.log(res.data)
                    ElMessage.error("修改作业成绩失败，请联系管理员")
                    }
                }).catch(e=>{
                console.log(e)
                })
}
// 主界面翻页
  function handleSizeChange(val){
    pageSize.value = val
    requestTclass()
  }
  function handleCurrentChange(val){
    currentPage.value = val
    requestTclass()
  }
  //难度颜色
  function tagColor(tag){
            if(tag==='hard')
            {
                return 'danger'
            }
            else if(tag==='easy')
            {
                return 'success'
            }
            else if(tag==='middle')
            {
                return 'warning'
            }
        }
</script>

<style scoped>
    .exam {
        width: 100%;
    }

    .filter-container {
        padding-bottom: 10px;
    }

    .filter-item {
        display: inline-block;
        vertical-align: middle;
        margin-bottom: 10px;
    }

    .item-input {
        width: 200px;
        margin-right: 5px;
    }

    .filter-container .filter-item:nth-child(3), .filter-container .filter-item:nth-child(4) {
        margin-left: 16px;
    }

    .exam-list {
        width: 100%;
    }

    .pagination-container {
        margin-top: 30px;
    }

    .exam-list .col2-cell-style {
        color: #409EFF;
        cursor: pointer;
    }

    .filter-bar {
        width: 100%;
        padding-bottom: 10px;
    }

    .filter-bar .el-input {
        width: 200px;
        margin-right: 5px;
    }

    .filter-bar .item-margin-left-16 {
        margin-left: 16px;
    }

    .el-dialog .el-table .col2-cell-style {
        color: #409EFF;
        cursor: pointer;
    }

    .el-dialog .stu-paper-container {
        margin: 0 20px;
    }

    .el-dialog .stu-paper-container h1 {
        text-align: center;
        font-size: 2.5em;
    }

    .el-dialog .stu-paper-container h3 {
        text-align: left;
    }

    .el-dialog .stu-paper-container .el-row {
        margin-bottom: 30px;
    }

    .el-dialog .stu-paper-container .stu-answer {
        margin-left: 20px;
    }

    .el-dialog .stu-paper-container .stu-paper-footer {
        text-align: right;
        margin-top: 30px;
    }

    .el-dialog .paper-container {
        margin: 0 20px;
    }

    .el-dialog .paper-container .paper-header h1 {
        text-align: center;
        font-size: 2.5em;
    }

    .el-dialog .paper-container .paper-info {
        text-align: center;
        padding: 20px;
    }

    .el-dialog .paper-container .paper-info h3 {
        display: inline-block;
        width: 25%;
    }

    .paper-container .paper-content {
        padding: 20px;
    }

    .take-up-header {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .take-up-header .header-icon {
        display: flex;
        color: #f8bb86;
        position: relative;
        justify-content: center;
        width: 5em;
        height: 5em;
        margin: 0 auto 1.875em;
        border: .25em #facea8 solid;
        border-radius: 50%;
        line-height: 5em;
        box-sizing: content-box;
    }

    .take-up-header .header-icon .icon-text {
        font-size: 3.75em;
    }

    .take-up-header .header-title {
        display: block;
        position: relative;
        max-width: 100%;
        margin: 0 0 0.4em;
        padding: 0;
        color: #595959;
        font-size: 2em;
        font-weight: 600;
        text-align: center;
        text-transform: none;
        word-wrap: break-word;
    }

    .take-up-content {
        color: #545454;
        font-size: 1.25em;
        font-weight: 300;
        text-align: center;
    }

    .transfeLayout {
        margin-left: 120px;
        margin-bottom: 25px;
    }

    .transfeTitle {
        width: 120px;
        height: 0px;
        padding-left: 12px;
        margin-bottom: 0px;
    }

    .problem-detail .problem-header {
        background-color: #16a085;
        color: #fff;
        padding: 10px;
    }

    .problem-body {
        padding: 20px;
        background-color: white;
    }

    .problem-body .border-top-style, .checkpoints {
        border-top: 5px solid #16a085;
        padding-top: 10px;
        margin-top: 30px;
    }

    .problem-body .border-top-style .description .first-checkpoint {
        border-top-width: 0;
        padding-top: 0;
        margin-top: 0;
    }

    .problem-body .sample {
        border-top-color: #ff7373;
    }

    .problem-body .description, .checkpoints-body .description {
        color: #666;
        margin-left: 20px;
    }

    .problem-detail h4 {
        font-size: 18px;
        margin-top: 4px;
    }

    .problem-detail h5 {
        font-size: 17px;
    }

    .problem-detail h6 {
        font-size: 16px;
    }

    .problem-detail h4, .problem-detail h5, .problem-detail h6 {
        font-weight: 500;
        margin: 10px 0;
        text-transform: uppercase;
    }

    .problem-detail p {
        margin-bottom: 10px;
    }

    .problem-detail .sample pre {
        display: block;
        padding: 10px;
        margin: 0 0 10px;
        font-size: 13px;
        line-height: 20px;
        word-break: break-all;
        word-wrap: break-word;
        white-space: pre-wrap;
        background-color: #f5f5f5;
        border: 1px solid rgba(0, 0, 0, 0.15);
        border-radius: 4px;
    }



    .p-operation {
        background-color: white;
        padding: 10px;
        border-top: 4px solid #16a085;
    }

    .p-operation .op-list {
        font-size: 14px;
        line-height: 2;
    }

    .code {
        border: 1px solid lightseagreen;
    }

    .op-list ul {
        list-style: none;
        padding-left: 0;
    }

    .op-list ul .op-li {
        color: #16a085;
        cursor: pointer;
    }

    .op-list ul .li-score {
        font-size: 16px;
        font-weight: bold;
        font-style: italic;
    }


</style>
